
"""
13. 罗马数字转整数
https://leetcode.cn/problems/roman-to-integer/description/?envType=study-plan-v2&envId=top-interview-150
"""
class Solution:

    SYMBOL_VALUES = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }

    def romanToInt(self, s: str) -> int:
        ans = 0
        n = len(s)
        for i, ch in enumerate(s):
            # 当前字符的值
            value = Solution.SYMBOL_VALUES[ch]
            # 如果下一个字符的值大于当前字符的值，则当前字符的值应该被减去
            if i < n - 1 and value < Solution.SYMBOL_VALUES[s[i + 1]]:
                ans -= value
            # 否则，当前字符的值应该被加上
            else:
                ans += value
        return ans

if __name__ == '__main__':
    print(Solution().romanToInt("III"))
    print(Solution().romanToInt("IV"))
    print(Solution().romanToInt("IX"))
    print(Solution().romanToInt("LVIII"))
    print(Solution().romanToInt("MCMXCIV"))
    print(Solution().romanToInt("MMMCMXCIX"))
